<template>
	<div :class="[prefixCls+'-carousel']" @mouseenter="handleMouseEnter" @mouseleave="handleMouseLeave" :style="{height:height?height:''}">
		<div :class="[prefixCls+'-carousel-list']">
			<div :class="[prefixCls+'-carousel-list-track']" ref="carouselTrack">
				<slot></slot>
			</div>
		</div>
        <button @click="prev" :class="{'prev':true,[prefixCls+'-carousel-arrow']:true,'disabled':!loop&&active==1,[arrow]:true}" v-if="arrow!='never'">
        	<i class="icon icon-arrow-left"></i>
        </button>
        <button @click="next" :class="{'next':true,[prefixCls+'-carousel-arrow']:true,'disabled':!loop&&active==count,[arrow]:true}" v-if="arrow!='never'">
        	<i class="icon icon-arrow-right"></i>
        </button>
        <ul :class="{[prefixCls+'-carousel-dots']:true,[prefixCls+'-carousel-dots-'+dots]:dots}" v-if="dots!='none'">
        	<li v-for="item in count" :key="item" :class="{on:(item)==active}" @click="dotsClick(item)" @mouseenter="dotsHover(item)">
        		<button>{{item}}</button>
        	</li>
        </ul>
	</div>
</template>

<script>
import {prefixCls} from '../prefix'

export default {
	name: `${prefixCls}Carousel`,
	props:{
		value: {
			type: Number,
			default: 1
		},
		// 是否开启循环
		loop: {
			type: Boolean,
			default: false
		},
		// 自动切换的时间间隔，单位ms
		delay: {
			type: Number,
			default: 3000
		},
		// 是否自动切换
		autoplay: {
			type: Boolean,
			default: false
		},
		// 指示器的触发方式
		trigger: {
			type: String,
			default: 'click'
		},
		// 走马灯的高度
		height: {
			type: String,
		},
		// 指示器的位置，可选值为 inside （内部），outside（外部），none（不显示）
		dots: {
			type: String,
			default: 'inside'
		},
		// 切换箭头的显示时机
		arrow: {
			type: String,
			default: 'hover'
		}
	},
	data() {
		return {
			prefixCls: prefixCls,
			count:'',	//轮播总数量
			active:this.value,	//当前位置
			time:null,	//定时器
			arrowAlign:'',	//prev,next控制时判断方向
			isArrowClick:true,	//左右点击必须在动画结束之后,防止动画过程中重复点击
		}
	},
	methods:{
		//下一张
		next() {
			if(!this.isArrowClick) return false;
			if(!this.loop && this.active == this.count) {
				return false
			}else{
				if(this.active==this.count){
					this.active=1;
				}else{
					this.active++;
				}
				this.arrowAlign = 'next'
				this.activeIndex(this.active)
			}
		},
		//上一张
		prev() {
			if(!this.isArrowClick) return false;
			if(!this.loop && this.active == 1) {
				return false
			}else{
				if(this.active<2){
					this.active=this.count
				}else{
					this.active--
				}
				this.arrowAlign = 'prev'
				this.activeIndex(this.active)
				
			}
		},
		// 当前显示
		activeIndex(num) {
			const _this = this
			this.$children.map(function(item,i){
				if(i === _this.active) {
					item.active = true
				}else{
					item.active = false
				}
			})
			this.scrollPostion(num)
		},
		// 循环，前后克隆一个
		loopclone() {
			if(this.loop) {
				const track = this.$refs.carouselTrack
				let cloneFirst = this.$children[0].$el.cloneNode(true)
				let cloneLast = this.$children[this.count-1].$el.cloneNode(true)
				track.appendChild(cloneFirst)
				track.insertBefore(cloneLast, track.children[0])
			}
			this.scrollPostion(this.active)
		},
		// 滚动位置
		scrollPostion(num) {
			const _this = this;
			const track = this.$refs.carouselTrack;
			let nums = num-1;
			this.isArrowClick = false;
			if(this.loop) {
				nums = num
				if(this.arrowAlign == 'prev' && nums == this.count) {
					track.style.transform = 'translate3d(0%, 0px, 0px)'
					track.style.transition = 'transform 500ms ease'
					setTimeout(()=>{
						track.style.transform = 'translate3d('+(-nums*100)+'%, 0px, 0px)'
						track.style.transition = 'transform 0ms ease'
					},500)
				}else if(this.arrowAlign == 'next' && nums == 1) {
					track.style.transform = 'translate3d('+(-(this.count+1)*100)+'%, 0px, 0px)'
					track.style.transition = 'transform 500ms ease'
					setTimeout(()=>{
						track.style.transform = 'translate3d('+(-nums*100)+'%, 0px, 0px)'
						track.style.transition = 'transform 0ms ease'
					},500)
				}else{
					track.style.transform = 'translate3d('+(-nums*100)+'%, 0px, 0px)'
					track.style.transition = 'transform 500ms ease'
				}
			}else{
				track.style.transform = 'translate3d('+(-nums*100)+'%, 0px, 0px)'
				track.style.transition = 'transform 500ms ease'
			}
			setTimeout(()=>{
				_this.isArrowClick = true
			},500)
			this.$emit('change',num)
		},
		// 控制器跳转
		dotsClick(num) {
			let _this = this;
			if(this.trigger != 'click') return false 
			this.active = num;
			setTimeout(()=>{
				_this.scrollPostion(num)
			},100)
		},
		// 控制器跳转
		dotsHover(num) {
			let _this = this;
			if(this.trigger != 'hover') return false
			this.active = num;
			setTimeout(()=>{
				_this.scrollPostion(num)
			},100)
		},

        // 自动播放，必须是可循环轮播方式
        _autoPlay() {
            if (this.autoplay && this.loop) {
                this.timer = setInterval(() => {
                    this.next();
                }, this.delay);
            }
        },
        // 清除定时器方法
        _clearIntervalFn() {
            clearInterval(this.timer);
            this.timer = null;
        },
        // 鼠标移入清除定时器
        handleMouseEnter() {
            this._clearIntervalFn();
        },
        // 鼠标移出开启自动播放
        handleMouseLeave() {
            this._autoPlay();
        },
        // 初始化
        init() {
			this.count = this.$children.length;//设置总数
			this.activeIndex(this.active)
        	this._autoPlay()//自动播放
        	this.loop?this.loopclone():''//轮播，前后克隆
        },
	},
	mounted() {
		this.init()
	},
	watch:{
		autoplay(val) {
			if(val) {
				this._autoPlay();
			}else{
            	clearInterval(this.timer);
            	this.timer = null;
			}
		},
		active(newval,oldval) {
			if(newval > oldval) {
				this.arrowAlign = 'next'
			}else {
				this.arrowAlign = 'prev'
			}
		}
	},
    beforeDestroy() {
        this._clearIntervalFn();
        this.timer = null;
    },
}
</script>
